import axios from 'axios'
export default {
    namespaced: true,
    state() {
        return {
            list: [{
                "id": 100001,
                "name": "低帮城市休闲户外鞋天然牛皮COOLMAX纤维",
                "price": 128,
                "count": 1,
                "thumb": "https://yanxuan-item.nosdn.127.net/3a56a913e687dc2279473e325ea770a9.jpg"
            },
            {
                "id": 100002,
                "name": "网易味央黑猪猪肘330g*1袋",
                "price": 39,
                "count": 10,
                "thumb": "https://yanxuan-item.nosdn.127.net/d0a56474a8443cf6abd5afc539aa2476.jpg"
            },
            {
                "id": 100003,
                "name": "KENROLL男女简洁多彩一片式室外拖",
                "price": 128,
                "count": 2,
                "thumb": "https://yanxuan-item.nosdn.127.net/eb1556fcc59e2fd98d9b0bc201dd4409.jpg"
            },
            {
                "id": 100004,
                "name": "云音乐定制IN系列intar民谣木吉他",
                "price": 589,
                "count": 1,
                "thumb": "https://yanxuan-item.nosdn.127.net/4d825431a3587edb63cb165166f8fc76.jpg"
            }],
        }
    },
    mutations: {
        updateList(state, newList) {
            state.list = newList
        },
        updateCount(state, obj) {
            state.list.forEach((item) => {
                if (item.id === obj.id) {
                    item.count = obj.newCount
                }
            })

        }
    },
    actions: {
        async getList(context) {
            const res = await axios.get('http://localhost:3000/cart')
            context.commit('updateList', res.data)
        },
        async updateCountAsync(context, obj) {
            context.commit('updateCount', obj)
        }
    },
    getters: {
        total(state) {
            return state.list.reduce((sum, item) => sum + item.count, 0)
        },
        totalPrice(state) {
            return state.list.reduce((sum, item) => sum + item.price * item.count, 0)
        }
    },
}